<!--系统日志收集记录-->
<template>
  <div class="bottom-record">
    <div class="record-title">
      <span>{{$t('System-log-record')}}</span>
    </div>
    
    <!--过滤选项-->
    <div class="check-filter-box">
      <!--仅显示收集成功结果：-->
      <span>
        {{$t('Only-show-collect-ok')}}：
        <a-checkbox v-model="collect_value" @change="changeCollectValue"></a-checkbox>
      </span>
      <!-- 仅显示未备份： -->
      <span>
        {{$t('Show-only-non-backup')}}：
        <a-checkbox v-model="backup_value" @change="changeBackupCheck"></a-checkbox>
      </span>
      <!-- 仅显示包未清除的记录： -->
      <span>
        {{$t('Show-only-records-package')}}：
        <a-checkbox v-model="packet_clear_value" @change="changePacketCheck"></a-checkbox>
      </span>
    </div>

    <!--表格-->
    <div style="padding:15px">
      <a-table :columns='columns' :dataSource='tableData' :loading="tableLoading" size='small' bordered
					:pagination='pagination' :rowKey="(record) =>record.id" :locale="defaultSetting">
        <!--收集结果-->
        <template slot="result" slot-scope="text, record">
          <!--成功-->
          <div v-if="text==1">
            <span class="green-circle"></span><span>{{$t('Success')}}</span>
          </div>
          <!--失败-->
          <div v-else-if="text==0">
            <span class="red-circle"></span><span>{{$t('Fail')}}</span>
          </div>
        </template>
        <!--已备份-->
        <template slot="backup" slot-scope="text, record">
          <!--是-->
          <div v-if="text==1">
            <span class="green-circle"></span><span>{{$t('Yes')}}</span>
          </div>
          <!--否-->
          <div v-else-if="text==0">
            <span class="red-circle"></span><span>{{$t('No')}}</span>
          </div>
        </template>

        <!--日志大小-->
        <template slot="size" slot-scope="text, record">
          <span v-if="text">{{text}}</span>
          <span v-else>-</span>
        </template>

        <!--当前状态-->
        <template slot="status" slot-scope="text, record">
          <!--包已清除-->
          <div v-if="text==0">
            <span class="green-circle"></span><span>{{$t('Package-cleared')}}</span>
          </div>
          <!--包未清除-->
          <div v-else-if="text==1">
            <span class="red-circle"></span><span>{{$t('Package-not-cleared')}}</span>
          </div>
          <span v-else>-</span>
        </template>
        <template slot="operation" slot-scope="text, record">
          <!--下载-->
          <div class="img-box" v-userAuth="'E10-5'">
            <a-tooltip>
              <template slot="title">
                {{$t('Download')}}
              </template>
              <!-- <i v-if="record.state == 1" class="icon icon-download16f table-icon" @click="downloadLog(record)"></i>
              <i v-else class="icon icon-download16f img-cannot-click grey-icon"></i> -->
              <!-- <a :href='`http://${record.manage_ip}:8001/download/${record.name}`' download> -->
                <a v-if="record.state == 1" :href='getDownloadHref(record)' download>
                  <Iconfont class="icon table-icon" type="icon-download16f"></Iconfont>
              <!-- <Iconfont v-if="record.state == 1" class="icon table-icon" type="icon-download16f" @click="downloadLog(record)"></Iconfont> -->
              </a>
              <Iconfont v-else class="icon img-cannot-click grey-icon" type="icon-download16f"></Iconfont>
            </a-tooltip>
          </div>
          <!--清除包-->
          <div class="img-box" v-userAuth="'E10-4'">
            <a-tooltip>
              <template slot="title">
                {{$t('Clear-package')}}
              </template>
              <!-- <i v-if="record.state == 1" class="icon icon-error64f table-icon" @click="delSysLog(record)"></i>
              <i v-else class="icon icon-error64f img-cannot-click grey-icon"></i> -->
              <Iconfont v-if="record.state == 1" class="icon table-icon" type="icon-error64f" @click="delSysLog(record)"></Iconfont>
              <Iconfont v-else class="icon img-cannot-click grey-icon" type="icon-error64f"></Iconfont>
            </a-tooltip>
          </div>
          <!--一键备份-->
          <div class="img-box" v-userAuth="'E10-6'">
            <a-tooltip>
              <template slot="title">
                {{$t('One-click-backup')}}
              </template>
              <!-- <i v-if="record.state == 1" class="icon icon-copy16f table-icon" @click="backUpFun(record)"></i>
              <i v-else class="icon icon-copy16f img-cannot-click grey-icon"></i> -->
              <Iconfont v-if="record.state == 1" class="icon table-icon" type="icon-copy16f" @click="backUpFun(record)"></Iconfont>
              <Iconfont v-else class="icon img-cannot-click grey-icon" type="icon-copy16f"></Iconfont>
            </a-tooltip>
          </div>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'
import request from '@/request/request'

export default {
  name: "SystemLogRecord",
  data() {
    return {
      collect_value: false,
      backup_value: false,
      packet_clear_value: false,
      tableData: [],
      tableData_copy: [],
      tableLoading: false,
      columns: [
        { title: this.$t('Log-name'), dataIndex: 'name', key: 'name', ellipsis: true, },//日志名称
        { title: this.$t('Manage-network'), dataIndex: 'manage_ip', key: 'manage_ip', ellipsis: true, },//管理网络
        { title: this.$t('Node-name'), dataIndex: 'hostname', key: 'hostname', ellipsis:true, },//节点名称
        { title: this.$t('Operation-user'), dataIndex: 'username', key: 'username', ellipsis: true, },//操作用户
        { title: this.$t('Collection-time'), dataIndex: 'collect_time', key: 'collect_time', ellipsis: true, },//收集时间
        { title: this.$t('Collect-results'), dataIndex: 'result', key: 'result', scopedSlots:{customRender:'result'}, ellipsis: true, },//收集结果
        { title: this.$t('Log-size'), dataIndex: 'size', key: 'size', ellipsis: true, scopedSlots:{customRender:'size'}, },//日志大小
        { title: this.$t('Backed-up'), dataIndex: 'backup', key: 'backup', scopedSlots:{customRender:'backup'}, ellipsis: true, },//已备份
        { title: this.$t('Current-state'), dataIndex: 'state', key: 'state', scopedSlots:{customRender:'status'}, ellipsis: true, },//当前状态
        { title: this.$t('Operate'), dataIndex: 'oper', key: 'oper', scopedSlots:{customRender:'operation'}, ellipsis: true, },
      ],
      pagination:{
        defaultPageSize:5,
        showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
        showSizeChanger:true,
        pageSizeOptions:['5','10','15'],
        onShowSizeChange:(current,pageSize)=>this.pageSize = pageSize,
				buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
      },
      defaultSetting: {emptyText:<EmptyData />},
      // userId: localStorage.getItem('user_id')
    }
  },

  watch: {
    getlanguage() {
      this.columns = [
        { title: this.$t('Log-name'), dataIndex: 'name', key: 'name', ellipsis: true, },//日志名称
        { title: this.$t('Manage-network'), dataIndex: 'manage_ip', key: 'manage_ip', ellipsis: true, },//管理网络
        { title: this.$t('Node-name'), dataIndex: 'hostname', key: 'hostname', ellipsis:true, },//节点名称
        { title: this.$t('Operation-user'), dataIndex: 'username', key: 'username', ellipsis: true, },//操作用户
        { title: this.$t('Collection-time'), dataIndex: 'collect_time', key: 'collect_time', ellipsis: true, },//收集时间
        { title: this.$t('Collect-results'), dataIndex: 'result', key: 'result', scopedSlots:{customRender:'result'}, ellipsis: true, },//收集结果
        { title: this.$t('Log-size'), dataIndex: 'size', key: 'size', ellipsis: true, scopedSlots:{customRender:'size'}, },//日志大小
        { title: this.$t('Backed-up'), dataIndex: 'backup', key: 'backup', scopedSlots:{customRender:'backup'}, ellipsis: true, },//已备份
        { title: this.$t('Current-state'), dataIndex: 'state', key: 'state', scopedSlots:{customRender:'status'}, ellipsis: true, },//当前状态
        { title: this.$t('Operate'), dataIndex: 'oper', key: 'oper', scopedSlots:{customRender:'operation'}, ellipsis: true, },
      ];
    },

    "$store.state.isUpdateSysCollectRecord"(newValue) {
      if(newValue) {
        this.getSystemCollectRecord();
        this.$store.commit('updateCollectRecord', false);
      }
    },
  },

  computed:{
		getlanguage(){
			return this.$store.state.language
		}
	},

  mounted() {
    this.getSystemCollectRecord();
  },

  methods: {
    // 返回下载地址
    getDownloadHref(record) {
       return `${this.$protocolStr}${record.manage_ip}${this.$portStr}download/${record.name}`;
    },
    //获取系统日志收集记录
    getSystemCollectRecord() {
      this.tableLoading = true;
      request('get', 'logmanage/syslog/', {
        // params: {
          // user_id: this.userId
        // }
      }).then(res => {
        // console.log('获取系统日志收集记录', res)
        this.tableData = res.data;
        this.tableData_copy = res.data;
        this.filterTableData();
      }).catch(err => {
        // console.log(err);
      }).finally(() => {
        this.tableLoading = false;
      })
    },

    //筛选方法
    filterTableData() {
      // collect_value
      // backup_value
      // packet_clear_value
      if(!this.collect_value && !this.backup_value && !this.packet_clear_value) {
        this.tableData = this.tableData_copy;
        return;
      }
      let finalData = this.tableData_copy;
      //仅显示收集成功结果
      if(this.collect_value) {
        finalData = finalData.filter(item => {
          return item.result == 1;
        })
      }
      //仅显示未备份
      if(this.backup_value) {
        finalData = finalData.filter(item => {
          return item.backup == 0;
        })
      }
      //仅显示包未清除的记录
      if(this.packet_clear_value) {
        finalData = finalData.filter(item => {
          return item.state == 1;
        })
      }
      this.tableData = finalData;
    },

    //改变是否仅显示收集成功结果
    changeCollectValue() {
      // console.log(this.collect_value)
      this.filterTableData();
    },

    //改变是否仅显示未备份
    changeBackupCheck() {
      this.filterTableData();
    },

    //改变是否仅显示包未清除的记录
    changePacketCheck() {
      this.filterTableData();
    },

    //下载
    downloadLog(record) {
      // this.tableLoading = true;
      this.$emit('changeSpinStatus', true);
      this.$message.success(this.$t('Downloading'));
      request('post', 'logmanage/syslog/download',{
        name: record.name
      },{
        responseType: 'blob'
      }).then(res => {
        // console.log('下载日志', res)
        if(res.status == 200) {
          this.downloadZip(res.data, record.name);
        }else {
          this.$message.error(this.$t('Download-fail'));
        }
      }).catch(err => {
        // console.log(err)
      }).finally(() => {
        // this.tableLoading = false;
        this.$emit('changeSpinStatus', false);
      })
    },
    //二进制流下载zip
    downloadZip(res, name) {
      let blob = new Blob([res], {type: `application/zip;`});
      // 获取heads中的filename文件名
      let downloadElement = document.createElement('a');
      // 创建下载的链接
      let href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      // 下载后文件名
      downloadElement.download = name;
      document.body.appendChild(downloadElement);
      // 点击下载
      downloadElement.click();
      // 下载完成移除元素
      document.body.removeChild(downloadElement);
      // 释放掉blob对象
      window.URL.revokeObjectURL(href);
      this.$message.success(this.$t('Download-success'));
    },

    //清除包
    delSysLog(record) {
      let _this = this;
      this.$confirm({
        title: this.$t('Clear-system-log'),
        content: this.$store.state.language == 'zh'?
        `清除节点${record.hostname}已经收集的系统日志后，如需重新下载需要重新收集，该过程需要一定时间。您确定要清除吗？`
        :`After clearing the system logs that have been collected by node ${record.hostname}, if you need to download again, you need to collect again. This process takes some time. Are you sure you want to clear?`,
        cancelText:this.$t('Cancel'),
        okText:this.$t('Sure'),
        okType:'danger',
        onOk(){
          _this.tableLoading = true;
          request('DELETE', 'logmanage/syslog/',{
            // data: {
              id: record.id, //日志主键
              name: record.name,  //日志名称
              node: record.hostname,
              ipaddr: record.manage_ip
            // }
          }).then(res => {
            // console.log('清除包',res)
            _this.model(res.data.id) //返回模板
            _this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
            _this.getSystemCollectRecord();
            _this.$emit('updateSystemLog');
          }).catch(err => {
            // console.log(err)
          }).finally(() => {
            _this.tableLoading = false;
          })
        },
        onCancel(){
          return;
        }
      })
    },

    //一键备份
    backUpFun(record) {
      this.tableLoading = true;
      request('post', 'logmanage/syslog/default/backup',{
        log_name: record.name, //日志名称
        log_id: record.log_id, //日志主键id,
        ipaddr: record.manage_ip
      }).then(res => {
        // console.log('一键备份', res)
        this.model(res.data.id) //返回模板
        this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
      }).catch(err => {
        // console.log(err);
      }).finally(() => {
        this.tableLoading = false;
      })
    },
  },
}
</script>
<style scoped>
  .bottom-record {
    height: 100%;
    margin: 15px 0;
    background-color: #fff;
    box-shadow: 1px 2px 10px 0px rgba(0, 0, 0, 0.2);
  }
  .record-title {
    padding: 10px 15px;
    border-bottom: 1px solid #cdcdcd;
  }
  .check-filter-box {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
  }
  .check-filter-box span {
    line-height: 32px;
    margin: 0 15px;
  }
  .img-box {
    display: inline-block;
    margin: 0 8px;
  }
  .img-cannot-click {
    cursor: not-allowed;
  }
  .table-icon {
    cursor: pointer;
    color: var(--themeColor);
  }
  .grey-icon {
    color: #d6d6d6;
  }
</style>